package com.washmadam.service.service.service.impl;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.washmadam.service.common.enums.DeleteEnum;
import com.washmadam.service.common.enums.ServiceStatusEnum;
import com.washmadam.service.common.enums.StatusEnum;
import com.washmadam.service.db.dao.CustomerOrderServiceMapper;
import com.washmadam.service.db.dto.CustomerOrderService;
import com.washmadam.service.db.example.CustomerOrderServiceExample;
import com.washmadam.service.service.service.CustomerOrderServiceQueryService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class CustomerOrderServiceQueryServiceImpl implements CustomerOrderServiceQueryService {
	@Autowired
	private CustomerOrderServiceMapper customerOrderServiceMapper;
	@Override
	public CustomerOrderService getCurrentCustomerOrderServiceByOrderId(Long orderId,Integer currentNum) {
		CustomerOrderServiceExample example = new CustomerOrderServiceExample();
		example.createCriteria()
		   	   .andCustomerOrderIdEqualTo(orderId)
		       .andServiceNumEqualTo(currentNum)
		       .andStatusEqualTo(StatusEnum.ENABLE.getCode())
		       .andIsDeleteEqualTo(DeleteEnum.NORMAL.getCode());
	    example.setOrderByClause("id asc");
	    List<CustomerOrderService> custOrderServiceList = customerOrderServiceMapper.selectByExample(example);
	    if(CollectionUtils.isNotEmpty(custOrderServiceList)) {
	    	return custOrderServiceList.get(0);
	    }
	    //基本不太可能走到这一步;
	    CustomerOrderService orderService = new CustomerOrderService(); 
	    orderService.setServiceNum(currentNum);
	    orderService.setCustomerOrderId(orderId);
	    orderService.setServiceStatus(ServiceStatusEnum.NORMAL.getCode());
	    orderService.setStatus(StatusEnum.ENABLE.getCode());
	    customerOrderServiceMapper.insertSelective(orderService);
		return orderService;
	}
	@Override
	public List<CustomerOrderService> getAllCompletedCustomerOrderServiceByOrderId(Long orderId) {
		CustomerOrderServiceExample example = new CustomerOrderServiceExample();
		example.createCriteria()
		   	   .andCustomerOrderIdEqualTo(orderId)
		   	   .andServiceStatusIn(Lists.newArrayList(ServiceStatusEnum.UN_COMPLETED.getCode(),ServiceStatusEnum.COMPLETED.getCode()))
		       .andStatusEqualTo(StatusEnum.ENABLE.getCode())
		       .andIsDeleteEqualTo(DeleteEnum.NORMAL.getCode());
	    example.setOrderByClause("id desc");
	    List<CustomerOrderService> custOrderServiceList = customerOrderServiceMapper.selectByExample(example);
	    return custOrderServiceList;
	}
	@Override
	public CustomerOrderService getLastOrderServiceByOrderId(Long orderId) {
		List<CustomerOrderService> list = getAllCompletedCustomerOrderServiceByOrderId(orderId);
		if(CollectionUtils.isNotEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

}
